/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/


#include "d3d_local.h"
#include <cuda.h>
#include <builtin_types.h>
#include <cuda_runtime_api.h>
#include <cuda_d3d9_interop.h>
#include "fluid_shared.h"


extern "C" 
{
	void CUDA_SetupMRIData(char *host_ptr, int w, int h, int d);
	void CUDA_VisMRI(void* screen, int scr_width, int scr_height, float *matrix, float t);
}

static LPDIRECT3DTEXTURE9	screen;
static LPDIRECT3DVOLUMETEXTURE9	mri_data;


#define CUDA_CHECK(call)	\
	do {					\
		if (call!=cudaSuccess) { LOGF("^4CUDA Failed : %s\r\n^7", #call); }			\
		else { /*LOGF("^2CUDA Call : %s\r\n^7", #call);*/ }							\
	} while (0);




//
//	ECudaTestMRI::ECudaTestMRI
//
ECudaTestMRI::ECudaTestMRI(ED3DRenderSystem *rs)
{
	LOG_SPLIT("CUDA initialization");
	
	LPDIRECT3DDEVICE9 d3ddev = rs->d3ddev;

	//	Init CUDA stuff :
	CUDA_CHECK( cudaD3D9SetDirect3DDevice(d3ddev) );
	CUDA_CHECK( cudaThreadSynchronize() );

	uint w, h;
	rs->GetScreenSize(w, h);
	rs->Set2DViewMode();
	HRCALL(d3ddev->CreateTexture(w/2, h/2, 0, 0, D3DFMT_A32B32G32R32F, D3DPOOL_DEFAULT, &screen, NULL) );

	LoadSlices();

	CUDA_CHECK( cudaD3D9RegisterResource(screen,	cudaD3D9RegisterFlagsNone)	);
	CUDA_CHECK( cudaThreadSynchronize() );
	

	LOG_SPLIT("");
}



//
//	ECudaTestMRI::~ECudaTestMRI
//
ECudaTestMRI::~ECudaTestMRI(void)
{
	LPDIRECT3DDEVICE9 d3ddev = rs->d3ddev;
	LOG_SPLIT("CUDA shutting down");

	CUDA_CHECK( cudaD3D9UnregisterResource(screen)	);
	//CUDA_CHECK( cudaD3D9UnregisterResource(mri_data)	);

	SAFE_RELEASE(screen);
	SAFE_RELEASE(mri_data);

	//	Shutdown CUDA :	
    CUDA_CHECK( cudaThreadExit() );
	CUDA_CHECK( cudaThreadSynchronize() );

	LOG_SPLIT("");
}




void ECudaTestMRI::LoadSlices(void)
{
	const uint NUM_SLICES = 140;
	LPDIRECT3DDEVICE9 d3ddev = rs->d3ddev;

	vector<char> data;
	data.resize(256*256*NUM_SLICES, 0x80);	
	
	for (uint i=1; i<=NUM_SLICES; i++) {
	
		IFile *f = fs->FileOpen(va("data/mri/mri_p%03d.tga", i), FS_OPEN_READ);

		f->Seek( 18+256*3, FS_SEEK_BEGIN);	// skip 18-byte header and 256*3 palette.		
		f->Read( &data[(i-1) * 256*256], 256*256);
		
		fs->FileClose(f);
	}
	
	
	/*for (uint i=0; i<data.size(); i++) {
		data[i] = rand()%256;
	}  */

	CUDA_SetupMRIData(&data[0], 256,256, 140);
}


//
//	ECudaTestMRI::Run
//
void ECudaTestMRI::Run(void)
{
	IVar	*mri_dist	=	shell->RegisterVar("mri_dist", "-10", 0);
	IVar	*mri_fov	=	shell->RegisterVar("mri_fov", "90", 0);
	IVar	*mri_pitch	=	shell->RegisterVar("mri_pitch", "0", 0);

	LPDIRECT3DDEVICE9 d3ddev = rs->d3ddev;
	static float t = 0;
	const float dt = 0.01;
	t = t + dt;
	
	uint w, h;
	rs->GetScreenSize(w, h);
	rs->Set2DViewMode();

	HRCALL( d3ddev->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) );
	HRCALL( d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE) );
	HRCALL( d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
	HRCALL( d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );

	    CUDA_CHECK( cudaD3D9MapResources(1, (IDirect3DResource9**)&screen) );
		CUDA_CHECK( cudaThreadSynchronize() );

		void* screen_ptr;
		size_t pitch;
		CUDA_CHECK( cudaD3D9ResourceGetMappedPointer(&screen_ptr, screen, 0, 0) );
		CUDA_CHECK( cudaD3D9ResourceGetMappedPitch(&pitch, NULL, screen, 0, 0) );
		
		EMatrix4	T;
		T *= Matrix4RotateY(t);
		T *= Matrix4RotateX(deg2rad(mri_pitch->Float()));
		T *=  Matrix4Translate(0,0, mri_dist->Float());
		T *= Matrix4PerspectiveFovRH(deg2rad(mri_fov->Float()), 3.0f/4.0f, 2.0f, 200.0f);
		T =	 Matrix4Transpose( Matrix4Inverse(T) );
		//T =	 Matrix4Inverse(T);

		CUDA_VisMRI(screen_ptr, w/2, h/2, T.Ptr(), t);

	    CUDA_CHECK( cudaD3D9UnmapResources(1, (IDirect3DResource9**)&screen) );
		CUDA_CHECK( cudaThreadSynchronize() );
	
		//CopyTextureToTexture(tex[0], tex[1]);*/
			

	float fw = w/1;
	float fh = h/1;
	HRCALL( d3ddev->SetTexture(0, screen) );
	rs->DrawQuad( 0, 0,  w, h, 0, 1, 1, 0, 0xFFFFFFFF);	
}












